package com.example.mapinformationandroid.DataBase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.mapinformationandroid.Model.User;

import java.util.ArrayList;
import java.util.List;

public class DBManager {
    private Context context;
    private static DBManager instance;

    private SQLiteDatabase writableDatabase;

    public DBManager(Context context) {
        this.context = context;
        BaseDBHelper dbHelper = new BaseDBHelper(context, 1);
        writableDatabase = dbHelper.getWritableDatabase();
    }

    public static DBManager getInstance(Context context) {
        if (instance == null) {
            synchronized (DBManager.class) {
                if (instance == null) {
                    instance = new DBManager(context);
                }
            }
        }
        return instance;
    }

    public void insertUserdata(User user) {
        Log.d("insert user table", user.toString());
        ContentValues contentValues = new ContentValues();
        contentValues.put("id", user.getId());
        contentValues.put("name", user.getName());
        contentValues.put("head_picture", user.getHead_picture());
        contentValues.put("examine", user.getExamine());
        contentValues.put("support", user.getSupport());
        contentValues.put("password", user.getPassword());
        contentValues.put("token", user.getToken());
        contentValues.put("token", user.getToken());
        writableDatabase.insert("userTB", null, contentValues);

    }

    public List<User> queryUserbyID(int id) {
       List<User> list = new ArrayList<>();
        Cursor cursor = writableDatabase.query("userTB", null, "id" + "=?", new String[]{"1"}, null, null, null);

        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {
            User user = new User();
            user.setId(cursor.getInt(cursor.getColumnIndex("id")));
            user.setName(cursor.getString(cursor.getColumnIndex("name")));
            user.setHead_picture(cursor.getString(cursor.getColumnIndex("head_picture")));
            user.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            user.setExamine(cursor.getInt(cursor.getColumnIndex("examine")));
            user.setSupport(cursor.getInt(cursor.getColumnIndex("support")));
            user.setToken(cursor.getString(cursor.getColumnIndex("token")));
            list.add(user);
            //移动到下一位
            cursor.moveToNext();
        }
        return list;
    }


}

